import React, { useState, useRef, useEffect } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Space,
  Button,
  Form,
  Input,
  Badge,
  message,
  Drawer,
  Tabs,
  Modal,
  InputNumber,
  Checkbox,
  notification,
} from 'antd';
import { connect, FormattedMessage, useIntl } from 'umi';
import MyDataTable from '@/components/MyDataTable';
import { EmpSelectCmp, EmpSelect } from '@/components/FormItemSelect';
import request from '@/utils/request';
import QuickMenu from '@/components/QuickMenu';
import ProTable, { ProColumns } from '@ant-design/pro-table';

const { TabPane } = Tabs;
const apiURL = '/api/services/app/JobMtl/';

type PartBinItem = {
  id: string;
  pickNum: string;
  partNum: string;
  partDescription: string;
  um: string;
  tranQty: number;
  actTranQty: number;
  warehouseCode: string;
  binNum: string;
  lotNum: string;
};

const ViewPage: React.FC<any> = (props) => {
  const [params, setParams] = useState({});
  const [freshNum, setFreshNum] = useState(0);
  const [freshNum2, setFreshNum2] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  const [record, setRecord] = useState([]);
  const [record2, setRecord2] = useState<any[]>([]);
  const [empName, setEmpName] = useState('');
  const [actTab, setActTab] = useState('1');
  const [visible, setVisible] = useState(false);
  const [visible2, setVisible2] = useState(false);
  const [visible3, setVisible3] = useState(false);
  const [loading, setLoading] = useState(false);
  const [editSelectRow, setEditSelectRow] = useState<any>(null);
  const intl = useIntl();
  const formRef = useRef<any>();
  const formRef2 = useRef<any>();
  const proTbRef2 = useRef<any>();

  useEffect(() => {
    if (visible2 && formRef2.current) {
      formRef2.current.setFieldsValue(editSelectRow);
    }
  }, [visible2, editSelectRow]);

  const doubleClick = (record: any) => {
    console.log(record);
  };

  const onFinish = (values: any) => {
    if (actTab === '1') {
      setParams(values);
      setFreshNum(freshNum + 1);
    } else {
      setParams(values);
      setFreshNum2(freshNum2 + 1);
    }
  };

  const onFinish2 = () => {
    const obj = formRef2.current.getFieldsValue();
    setRecord2([obj]);
    returnMtl();
  };

  const resetForm = () => {
    formRef.current.resetFields();
  };

  const issueMtl = () => {
    if (record.length <= 0) {
      message.warning(intl.formatMessage({ id: 'pages.selectAtLeastOneRecord' }));
      return;
    }
    if (!empName || empName === '') {
      message.warning(intl.formatMessage({ id: 'pages.selectEmployeeRequired' }));
      return;
    }
    const data: any = [];
    record.forEach((element: any) => {
      data.push({
        jobNum: element.jobNum,
        asmSeq: element.assemblySeq,
        mtlSeq: element.mtlSeq,
        issueQty: element.pickQty - element.issuedQty,
        pickNum: element.pickNum,
        EmpID: empName,
        partNum: element.partNum,
        partDescription: element.partDescription,
        ium: element.ium,
        pickType: element.pickType,
        reqNum: element.reqNum,
        reqLine: element.reqLine,
      });
    });
    request(apiURL + 'IssueMtl', {
      method: 'POST',
      data,
    }).then((response) => {
      if (response && response.success) {
        if (response.result == 'ok')
          message.success(intl.formatMessage({ id: 'pages.issueMtlSuccess' }));
        else {
          notification.error({
            description: response.result,
            message: intl.formatMessage({ id: 'pages.issueMtlError' }),
            duration: 12,
          });
        }
        setRecord([]);
      }
      setLoading(false);
      setFreshNum(freshNum + 1);
    });
  };

  const returnMtl = () => {
    if (record2.length <= 0) {
      message.warning(intl.formatMessage({ id: 'pages.selectAtLeastOneRecord' }));
      return;
    }
    const data: any = [];
    record2.forEach((element: any) => {
      data.push({
        id: element.id,
        jobNum: element.jobNum,
        asmSeq: element.assemblySeq,
        mtlSeq: element.jobSeq,
        returnQty: element.actTranQty,
        whseCode: element.wareHouseCode,
        binNum: element.binNum,
        lotNum: element.lotNum,
        pickNum: element.tranReference,
        EmpID: element.empID,
        insp: element.insp,
        partNum: element.partNum,
        partDescription: element.partDescription,
        ium: element.um,
        pickType: element.jobNum ? 'JOB' : 'STK',
        reqNum: element.reqNum,
        reqLine: element.reqLine,
      });
    });
    setLoading(true);
    request(apiURL + 'ReturnMtl', {
      method: 'POST',
      data,
    }).then((response) => {
      if (response && response.success) {
        message.success(intl.formatMessage({ id: 'pages.returnMtlSuccess' }));
        setRecord2([]);
      }
      setLoading(false);
      setFreshNum2(freshNum2 + 1);
      setVisible2(false);
      setVisible3(false);
    });
  };

  const switchDraw = () => {
    setVisible(!visible);
  };

  const switchModal = (record?: any) => {
    setVisible2(!visible2);
    if (record) {
      record.insp = true;
      record.actTranQty = Math.abs(record.actTranQty);
      setEditSelectRow(record);
    }
  };

  const tabChange = (key: any) => {
    setActTab(key);
  };

  const getNewSelectRows = async () => {
    record2.forEach((element: PartBinItem) => {
      element.actTranQty = Math.abs(element.actTranQty);
    });
    return {
      data: record2,
      srccess: true,
    };
  };

  const batchReturnMtl = (v: boolean) => {
    if (v) {
      if (record2.length <= 0) {
        message.warning(intl.formatMessage({ id: 'pages.selectAtLeastOneRecord' }));
        return;
      }
    }
    setVisible3(v);
  };

  const checkQty = (rule: any, value: any, callback: any) => {
    if (value) {
      if (editSelectRow.actTranQty < value || value <= 0) {
        callback(intl.formatMessage({ id: 'pages.actTranQtyCheck' }));
      } else {
        callback();
      }
    } else {
      callback(intl.formatMessage({ id: 'pages.returnQty.required' }));
    }
  };

  const columns = [
    {
      title: <FormattedMessage id="pages.pickNum" />,
      dataIndex: 'pickNum',
      width: 100,
    },
    {
      title: <FormattedMessage id="pages.billNo" />,
      width: 80,
      render: (text: any, record: any) =>
        record.pickType === 'JOB'
          ? record.jobNum + '-' + record.assemblySeq + '-' + record.mtlSeq
          : record.reqNum + '-' + record.reqLine,
    },
    {
      title: <FormattedMessage id="pages.partNum" />,
      dataIndex: 'partNum',
      width: 90,
      render: (text: any, record: any) => (
        <span>
          {text} {record.issuedComplete ? <Badge status="success" /> : ''}
        </span>
      ),
    },
    {
      title: <FormattedMessage id="pages.partDescription" />,
      dataIndex: 'partDescription',
      ellipsis: true,
      width: 220,
    },
    {
      title: <FormattedMessage id="pages.opCode" />,
      dataIndex: 'opCode',
      width: 100,
    },
    {
      title: <FormattedMessage id="pages.pickQty" />,
      dataIndex: 'pickQty',
      align: 'center',
      width: 65,
    },
    {
      title: <FormattedMessage id="pages.issuedQty" />,
      dataIndex: 'issuedQty',
      align: 'center',
      width: 65,
    },
    {
      title: <FormattedMessage id="pages.pickUser" />,
      dataIndex: 'pickUser',
      width: 100,
    },
  ];

  const columns2 = [
    {
      title: <FormattedMessage id="pages.pickNum" />,
      dataIndex: 'tranReference',
      width: 145,
    },
    {
      title: <FormattedMessage id="pages.billNo" />,
      width: 120,
      render: (text: any, record: any) =>
        record.jobNum
          ? record.jobNum + '-' + record.assemblySeq + '-' + record.jobSeq
          : record.reqNum + '-' + record.reqLine,
    },
    {
      title: <FormattedMessage id="pages.partNum" />,
      dataIndex: 'partNum',
      width: 120,
    },
    {
      title: <FormattedMessage id="pages.partDescription" />,
      dataIndex: 'partDescription',
      ellipsis: true,
    },
    {
      title: <FormattedMessage id="pages.quantity" />,
      dataIndex: 'tranQty',
      align: 'center',
      width: 65,
    },
    {
      title: <FormattedMessage id="pages.issue.actTranQty" />,
      dataIndex: 'actTranQty',
      width: 80,
      align: 'center',
      render: (text: any) => Math.abs(text),
    },
    {
      title: <FormattedMessage id="pages.IUM" />,
      dataIndex: 'um',
      align: 'center',
      width: 60,
    },
    {
      title: <FormattedMessage id="pages.warehouseCode" />,
      dataIndex: 'wareHouseCode',
      align: 'center',
      width: 80,
    },
    {
      title: <FormattedMessage id="pages.binNum" />,
      dataIndex: 'binNum',
      align: 'center',
      width: 80,
    },
    {
      title: <FormattedMessage id="pages.lotNum" />,
      dataIndex: 'lotNum',
      align: 'center',
      width: 80,
    },
    {
      title: <FormattedMessage id="pages.issue.creationTime" />,
      dataIndex: 'creationTime',
      width: 200,
      valueType: 'dateTime',
    },
    {
      title: <FormattedMessage id="pages.issueUser" />,
      dataIndex: 'empID',
      width: 100,
    },
    {
      title: <FormattedMessage id="pages.operation" />,
      key: 'action',
      width: 100,
      fixed: 'right',
      render: (_: any, record: any) => (
        <Space>
          <Button size="small" type="ghost" danger onClick={() => switchModal(record)}>
            <FormattedMessage id="returnMtl" />
          </Button>
        </Space>
      ),
    },
  ];

  const columns3: ProColumns<PartBinItem>[] = [
    {
      title: <FormattedMessage id="pages.operation" />,
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            setEditSelectRow(record);
            action?.startEditable?.(record.id);
          }}
        >
          <FormattedMessage id="pages.edit" />
        </a>,
      ],
    },
    {
      title: <FormattedMessage id="pages.returnQty" />,
      dataIndex: 'actTranQty',
      width: 100,
      align: 'center',
      valueType: 'digit',
      formItemProps: {
        rules: [
          {
            required: true,
            validator: checkQty,
          },
        ],
      },
    },
    {
      title: <FormattedMessage id="pages.quantity" />,
      dataIndex: 'tranQty',
      align: 'center',
      width: 65,
      valueType: 'digit',
      editable: false,
    },

    {
      title: <FormattedMessage id="pages.partNum" />,
      dataIndex: 'partNum',
      width: 120,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.partDescription" />,
      dataIndex: 'partDescription',
      ellipsis: true,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.pickNum" />,
      dataIndex: 'tranReference',
      width: 145,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.jobNum" />,
      dataIndex: 'jobNum',
      width: 120,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.reqNum" />,
      dataIndex: 'reqNum',
      width: 120,
      editable: false,
    },

    {
      title: <FormattedMessage id="pages.IUM" />,
      dataIndex: 'um',
      align: 'center',
      width: 60,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.warehouseCode" />,
      dataIndex: 'wareHouseCode',
      align: 'center',
      width: 80,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.binNum" />,
      dataIndex: 'binNum',
      align: 'center',
      width: 80,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.lotNum" />,
      dataIndex: 'lotNum',
      align: 'center',
      width: 80,
      editable: false,
    },
    {
      title: <FormattedMessage id="pages.issue.creationTime" />,
      dataIndex: 'creationTime',
      width: 200,
      valueType: 'dateTime',
      editable: false,
    },
  ];

  const layout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  const layout2 = {
    labelCol: { span: 7 },
    wrapperCol: { span: 17 },
  };

  const rowSelection = {
    onChange: (_selectedKeys: any, selectedRows: any) => {
      setRecord(selectedRows);
    },
  };

  const rowSelection2 = {
    onChange: (_selectedKeys: any, selectedRows: any) => {
      setRecord2(selectedRows);
    },
  };

  return (
    <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
      <Card>
        <Tabs
          defaultActiveKey="1"
          onChange={tabChange}
          tabBarExtraContent={
            <Space key="S1">
              <QuickMenu path="/part/IssueMtl" icon="icon-document" title="pages.IssueMtl" />
              <EmpSelectCmp
                tooltip={intl.formatMessage({ id: 'pages.selectWDEmployee' })}
                showSearch
                width={100}
                name="userId"
                label={<FormattedMessage id="pages.employee" />}
                onChange={setEmpName}
                params={{
                  deptCode: 'WD',
                }}
              />
              <Button type="primary" onClick={() => issueMtl()} disabled={actTab == '2'}>
                <FormattedMessage id="pages.issueMtl" />
              </Button>
              <Button
                type="primary"
                danger
                onClick={() => batchReturnMtl(true)}
                disabled={actTab != '2'}
              >
                批量退料
              </Button>
              <Button type="default" onClick={switchDraw}>
                <FormattedMessage id="pages.search" />
              </Button>
            </Space>
          }
        >
          <TabPane tab={<FormattedMessage id="pages.issueHistory" />} key="1">
            <MyDataTable
              act="GetIssueMtl"
              columns={columns}
              freshNum={freshNum}
              pageSize={pageSize}
              control="JobMtl"
              doubleClick={doubleClick}
              rowSelection={rowSelection}
              params={params}
              pagination={true}
              size="small"
            />
          </TabPane>
          <TabPane tab={<FormattedMessage id="pages.issueHistory" />} key="2">
            <MyDataTable
              act="GetReturnMtl"
              columns={columns2}
              freshNum={freshNum2}
              pageSize={pageSize}
              control="PartTran"
              doubleClick={doubleClick}
              rowSelection={rowSelection2}
              scroll={{ x: 'max-content' }}
              size="small"
              params={params}
              pagination={true}
            />
          </TabPane>
        </Tabs>
      </Card>
      <Drawer
        title={<FormattedMessage id="pages.search" />}
        width={400}
        placement="right"
        closable={false}
        visible={visible}
        onClose={switchDraw}
        mask={true}
        maskClosable={true}
        footer={
          <Button type="primary" onClick={switchDraw}>
            <span>
            <FormattedMessage id="pages.close" /></span>
          </Button>
        }
      >
        <Form {...layout} ref={formRef} onFinish={onFinish}>
          <Form.Item label={<FormattedMessage id="pages.jobNum" />} name="jobNum">
            <Input />
          </Form.Item>
          <Form.Item label={<FormattedMessage id="pages.partNum" />} name="keywords">
            <Input />
          </Form.Item>
          <Form.Item label={<FormattedMessage id="pages.pickNum" />} name="pickNum">
            <Input />
          </Form.Item>
          <Form.Item label={<FormattedMessage id="pages.opCode" />} name="opCode">
            <Input />
          </Form.Item>
          <EmpSelect showSearch name="user" label={<FormattedMessage id="pages.pickUser" />} />
          <Form.Item wrapperCol={{ offset: 5 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                <FormattedMessage id="pages.search" />
              </Button>
              <Button type="default" onClick={resetForm}>
                <FormattedMessage id="pages.reset" />
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
      <Modal
        title={<FormattedMessage id="pages.returnMtl" />}
        visible={visible2}
        destroyOnClose={false}
        footer={null}
        onCancel={() => switchModal()}
      >
        <Form {...layout2} ref={formRef2} onFinish={onFinish2}>
          <Form.Item label="ID" name="id" hidden>
            <Input disabled />
          </Form.Item>
          <Form.Item label={<FormattedMessage id="pages.pickNum" />} name="tranReference">
            <Input disabled />
          </Form.Item>
          <Form.Item label={<FormattedMessage id="pages.jobNum" />}>
            <Input.Group compact>
              <Form.Item name="jobNum" noStyle>
                <Input style={{ width: 100 }} disabled />
              </Form.Item>
              <Form.Item name="assemblySeq" noStyle>
                <Input style={{ width: 50 }} disabled />
              </Form.Item>
              <Form.Item name="jobSeq" noStyle>
                <Input style={{ width: 50 }} disabled />
              </Form.Item>
            </Input.Group>
          </Form.Item>
          <Form.Item label={<FormattedMessage id="pages.reqNum" />}>
            <Input.Group compact>
              <Form.Item name="reqNum" noStyle>
                <Input style={{ width: 100 }} disabled />
              </Form.Item>
              <Form.Item name="reqline" noStyle>
                <Input style={{ width: 50 }} disabled />
              </Form.Item>
            </Input.Group>
          </Form.Item>
          <Form.Item label={<FormattedMessage id="pages.partNum" />} name="partNum">
            <Input disabled />
          </Form.Item>
          <Form.Item label={<FormattedMessage id="pages.partDescription" />} name="partDescription">
            <Input disabled />
          </Form.Item>
          <Form.Item label={<FormattedMessage id="pages.whseLocation" />}>
            <Input.Group compact>
              <Form.Item name="wareHouseCode" noStyle>
                <Input placeholder="warehouse" style={{ width: 100 }} disabled />
              </Form.Item>
              <Form.Item name="binNum" noStyle>
                <Input placeholder="binNum" style={{ width: 60 }} disabled />
              </Form.Item>
              <Form.Item name="lotNum" noStyle>
                <Input placeholder="lotNum" style={{ width: 100 }} disabled />
              </Form.Item>
            </Input.Group>
          </Form.Item>

          <Form.Item label={<FormattedMessage id="pages.returnMtlQty" />} style={{ marginBottom: 0 }}>
            <Input.Group compact>
              <Form.Item name="actTranQty">
                <InputNumber />
              </Form.Item>
              <Form.Item name="um">
                <Input disabled style={{ width: 60 }} />
              </Form.Item>
              <Form.Item name="empID">
                <Input disabled style={{ width: 100 }} />
              </Form.Item>
            </Input.Group>
          </Form.Item>
          <Form.Item name="insp" valuePropName="checked" wrapperCol={{ offset: 7 }}>
            <Checkbox defaultChecked={false}>
              <FormattedMessage id="pages.inspectionReq" />
            </Checkbox>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 7 }}>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                <span>
                  <FormattedMessage id="pages.submit" />
                </span>
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title={intl.formatMessage({ id: 'pages.batchReturnMtl' })}
        visible={visible3}
        destroyOnClose
        width="800px"
        footer={
          <Button key="button" type="primary" onClick={() => returnMtl()} loading={loading}>
            <span>
              <FormattedMessage id="pages.submit" />
            </span>
          </Button>
        }
        onCancel={() => batchReturnMtl(false)}
      >
        <ProTable<PartBinItem>
          actionRef={proTbRef2}
          columns={columns3}
          bordered
          request={async (_params = {}) => {
            setParams(_params);
            return getNewSelectRows();
          }}
          editable={{
            type: 'multiple',
            onSave: async (rowKey, data, row) => {
              const newArr: PartBinItem[] = [];
              record2.forEach((o: PartBinItem) => {
                if (o.id == row.id) {
                  newArr.push(data);
                } else {
                  newArr.push(o);
                }
              });
              setRecord2(newArr);
              proTbRef2.current.reload();
            },
            onDelete: async (rowKey, row) => {
              const items = record2.filter((o: PartBinItem) => o.id != row.id);
              setRecord2(items);
              proTbRef2.current.reload();
            },
          }}
          scroll={{ x: 'max-content', y: '300px' }}
          rowKey="id"
          search={false}
          pagination={false}
          headerTitle={false}
          toolBarRender={false}
        />
      </Modal>
    </PageHeaderWrapper>
  );
};

export default connect(({ Abp, user }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: user.currentUser,
}))(ViewPage);
